#ifndef DXDraw_h__
#define DXDraw_h__
#include <ddraw.h>
#include <Windows.h>
#include <io.h>
#include <math.h>
#include "Common.h"

#pragma warning(disable:4996)

#ifndef PI
#define PI 3.1415926535
#endif

#define DDRAW_INIT_STRUCT(ddstruct) { memset(&ddstruct,0,sizeof(ddstruct)); ddstruct.dwSize=sizeof(ddstruct); }
#define _RGB32BIT(a,r,g,b) ((b) + ((g) << 8) + ((r) << 16) + ((a) << 24))
#define RADIAN(angle) ((angle)*PI/180.0)
class DXDraw;

extern DXDraw* g_pDraw;

class DXDraw
{
protected:
	LPDIRECTDRAW          m_lpdd;             // dd4 object
	LPDIRECTDRAWSURFACE   m_lpddsprimary;    //  dd primary surface
	LPDIRECTDRAWSURFACE   m_lpddsback;       //  dd back surface
	LPDIRECTDRAWCLIPPER   m_lpddclipper;     //  dd clipper
	
	DDSURFACEDESC         m_ddsd;            //  a direct draw surface description struct
	DDBLTFX               m_ddbltfx;         //   used to fill

	int m_ScreenWidth;
	int m_ScreenHeight;
	int m_bpp;     //color depth.

	HINSTANCE m_mainInstance;
	HWND m_mainWnd;

	RECT m_clientRect;

protected:
	bool CreateWindowClipper();
	DWORD DDColorMatch(LPDIRECTDRAWSURFACE lpdds, COLORREF rgb);
	bool LoadBmpFileInfo(HWND hwnd, const char* pFilename, int* width, int* height);
	HRESULT RestoreAll();
	bool BeginDraw(LPDIRECTDRAWSURFACE lpdds,DDSURFACEDESC* pDesc);
	bool EndDraw(LPDIRECTDRAWSURFACE lpdds);
	
	int CopyBmpToSurface(LPDIRECTDRAWSURFACE lpdds, HBITMAP hbm, int ox, int oy, int width, int height);
	int LoadBmpToSurface(LPDIRECTDRAWSURFACE lpdds, const char* pcbitmap);

public:
	DXDraw(int width, int height, int bpp, HINSTANCE mainInstance, HWND mainWnd);
	int Initialize();

public:


	void Render();

	LPDIRECTDRAWSURFACE GetBackSurface();

	void SetClientRect(const RECT& crect);

	//------------------------------------util methods-------------------------------------------------

	//create a surface with bmp, their size are equal.
	LPDIRECTDRAWSURFACE CreateSurfaceWithBmp(const char* pBmp,int memoryFlag = DDSCAPS_SYSTEMMEMORY);
	
	//for convenience to read spr file. usually called by CSPR.
	LPDIRECTDRAWSURFACE CreateSurfaceWithData8(BYTE* pData, DWORD* pPal, int width, int height,int colorKey = -1);
	LPDIRECTDRAWSURFACE CreateSurfaceWithSprData(DWORD* pData, int width, int height,int colorKey = -1);
	
	LPDIRECTDRAWSURFACE CreateSurfaceWithData32(DWORD* pData, int width, int height, int colorKey = -1);
	LPDIRECTDRAWSURFACE CreateSurface(int width, int height, int flag, int colorKey = -1);
	
	HRESULT AlphaBlt(const LPDIRECTDRAWSURFACE dest, const LPDIRECTDRAWSURFACE src, const unsigned char alpha,
		POINT* destPoint,  RECT* srcRect,const bool isColorKeyed );
	HRESULT MirrorSurf(LPDIRECTDRAWSURFACE surf);
	LPDIRECTDRAWSURFACE RotateSurf(LPDIRECTDRAWSURFACE surf, double RotateAngle, COLORREF clrKey);
	void CleanSurface(LPDIRECTDRAWSURFACE surf,DWORD color);

	//debug
	void ShowCell();
};



#endif // DXDraw_h__